package com.hunzi.controller;

import com.github.pagehelper.PageInfo;
import com.hunzi.domain.Item;
import com.hunzi.domain.ItemCat;
import com.hunzi.service.ItemCatService;
import com.hunzi.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private ItemCatService itemCatService ;

    //注入在properties文件中定义的pageSize变量
    @Value ( "${pageSize}" )
    private  int pageSize ;



    //1、根据分类显示信息
    //注意： 通过浏览器访问地址传入cid和pageNum
    @RequestMapping("/selectByCid/{cid}/{pageNum}")
    public String selectByCid(@PathVariable int cid, @PathVariable int pageNum , Model model){
        //System.out.println ("商品分类id: "  +cid +  "   显示商品第几页: "+  pageNum + "  页面最大商品数量"+ pageSize);
        //1.调用分页方法
        PageInfo<Item> pageInfo = itemService.selectPageByCid ( cid, pageNum, pageSize );
        //2.将分页信息对象放入model
        model.addAttribute ( "pageInfo" , pageInfo );

        //3.根据商品分类id查询商品信息
        ItemCat itemCat = itemCatService.selectByPrimaryKey ( cid );
        model.addAttribute ( "itemCat",itemCat );
        return "category";
    }

    //2、根据商品id查询商品详细信息
    //根据浏览器访问地址传入id值
    @RequestMapping("/selectById/{id}")
    public String selectById(@PathVariable int id ,Model model ){
        Item item = itemService.selectByPrimaryKey ( id );
        model.addAttribute ( "item" , item );
        return "item";
    }

    //3、模糊查询商品信息
    @RequestMapping("/selectLikeName")
    public String selectLikeName(HttpServletRequest request , Model model){
        //System.out.println ("ajax方法请求成功");
        String  name = request.getParameter ( "$word" );
        List<Item> items = itemService.selectLikeName ( name );
        for (Item item : items) {
           String shopName = item.getName ();
            model.addAttribute ( "shopName" , shopName );
            System.out.println (shopName);
        }
        return "header";
    }

}
